package com.tensquare.base.controller;

import com.tensquare.base.pojo.Label;
import com.tensquare.base.service.LabelService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController //controller+ResponseBody
@CrossOrigin
@RequestMapping("/label")
public class LabelController {
  @Autowired
  LabelService labelService;

  @RequestMapping(method = RequestMethod.GET)
  public Result findAll(){
    return new Result(true,StatusCode.OK,"查询成功",labelService.findAll());
  }

  @RequestMapping(value = "/{labelId}",method = RequestMethod.GET)
  public Result findById(@PathVariable String labelId){
    // int ni = 1/0;//exception test
    return new Result(true,StatusCode.OK,"查询成功",labelService.findById(labelId));
  }

  @RequestMapping(method = RequestMethod.POST)//添加使用的是ＰＯＳＴ，而查询是采用的ＧＥＴ
  public Result save(@RequestBody Label label){//json转对象,使用RequestBody
    labelService.add(label);
    return new Result(true,StatusCode.OK,"插入成功");
  }


  @RequestMapping(value = "/{labelId}",method = RequestMethod.PUT)
  public Result update(@PathVariable String labelId,@RequestBody Label label){
    label.setId(labelId);
    labelService.update(label);
    return new Result(true,StatusCode.OK,"更新成功");
  }

  @RequestMapping(value = "/{labelId}",method = RequestMethod.DELETE)
  public Result deleteById(@PathVariable String labelId){
    labelService.deleteById(labelId);
    return new Result(true,StatusCode.OK,"删除成功");
  }

  @RequestMapping(value = "/search",method = RequestMethod.POST)
  public Result findSearch(@RequestBody Label label){//也可以转map
    List<Label> labelList = labelService.findSearch(label);
    return new Result(true,StatusCode.OK,"搜索成功",labelList);
  }

  @RequestMapping(value = "/search/{page}/{size}",method = RequestMethod.POST)
  public Result pageQuery(@RequestBody Label label
    ,@PathVariable("page") int page, @PathVariable("size")int size){//也可以转map

    Page<Label> labelPage = labelService.pageQuery(label,page,size);

    return new Result(true,StatusCode.OK,"搜索成功",
      new PageResult<Label>(labelPage.getTotalElements(),labelPage.getContent()));

  }

}
